package com.sly.slf4jmdc.interceptor;

import com.sly.slf4jmdc.common.util.TraceContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 日志拦截器
 *
 * @author SLY
 * @date 2022/3/10
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor {

    /**
     * 会话ID
     */
    private final static String TRACE_ID = TraceContext.TRACE_ID;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TraceContext.TRACE_ID);
        // 设置traceId
        if(StringUtils.isBlank(traceId)){
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(TRACE_ID, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除traceId
        MDC.remove(TRACE_ID);
    }
}
